package org.easydarwin.activitys;

import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.text.method.HideReturnsTransformationMethod;
import android.text.method.PasswordTransformationMethod;
import android.view.View;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;

import org.easydarwin.beans.LoginResult;
import org.easydarwin.beans.User;
import org.easydarwin.easyrtc.MainActivity;
import org.easydarwin.easyrtc.R;
import org.easydarwin.easyrtc.databinding.ActivityLoginBinding;
import org.easydarwin.network.NetConfig;
import org.easydarwin.network.NormalPostRequest;
import org.easydarwin.network.RequestManager;
import org.easydarwin.network.result.VolleyResult;
import org.easydarwin.util.AccountUtil;
import org.easydarwin.util.ListUtil;
import org.easydarwin.util.LogUtil;
import org.easydarwin.util.PreferenceManager;
import org.easydarwin.util.VolleyUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;

public class LoginActivity extends AppCompatActivity implements TextWatcher{

    private  ActivityLoginBinding dataBinding;
    private Handler handler = new MyHandler(this);
    public final int login_success = 0x1;// 登录成功
    private String account;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        dataBinding = DataBindingUtil.setContentView(this , R.layout.activity_login);
        dataBinding.loginInputAccount.addTextChangedListener(this);
        dataBinding.loginInputPassword.addTextChangedListener(this);

        onInputTextChange();
        String account = PreferenceManager.getInstance().getAccount();
        String pwd = PreferenceManager.getInstance().getCurrentUserPwd();

        if(!TextUtils.isEmpty(account)){
            dataBinding.loginInputAccount.setText(account);
        }

        if(!TextUtils.isEmpty(pwd)){
            dataBinding.loginInputPassword.setText(pwd);
        }
    }

    public void onInputTextChange() {
        dataBinding.loginSubmit.setEnabled(!TextUtils.isEmpty(dataBinding.loginInputAccount.getText()) && !TextUtils.isEmpty(dataBinding.loginInputPassword.getText()));
        dataBinding.passwordEye.setVisibility(TextUtils.isEmpty(dataBinding.loginInputPassword.getText()) ? View.GONE : View.VISIBLE);
    }

    public void onClickLogin(View view) {
        if (checkInput()){
            userLogin();
        }
//        gotoHelp();
    }

    private boolean checkInput(){
        if (TextUtils.isEmpty(dataBinding.loginInputAccount.getText())){
            return false;
        }
        return true;
    }

    private void userLogin(){
        account = dataBinding.loginInputAccount.getText().toString();
        String password = dataBinding.loginInputPassword.getText().toString();
        Map<String, String> map = new HashMap<String, String>();
        map.put("account", account);
        map.put("password", password);
        String url = NetConfig.getBaseUrl()+ NetConfig.userLogin;
        JSONObject jsonObject = new JSONObject(map);
        VolleyUtils.getInstance(this).sendPostRequest(url, jsonObject, new VolleyResult() {
            @Override
            public void success(String result, String method) { }

            @Override
            public void jsonSuccess(JSONObject result, String method) {
                Message msg = handler.obtainMessage();
                msg.what = login_success;
                LoginResult res = new Gson().fromJson(result.toString() , LoginResult.class);
                msg.obj = res;
                handler.sendMessage(msg);
            }

            @Override
            public void failure(String error, String method) { }
        } , true );

    }



    private void loginSuccess(User user){
        if(null != user){
            LogUtil.i("================ user = " + user.toString());
            PreferenceManager.getInstance().setCurrentUserName(user.getNickname());
            PreferenceManager.getInstance().setAccount(account);
            PreferenceManager.getInstance().setCurrentUserPwd(dataBinding.loginInputPassword.getText().toString());
            gotoHelp(user);
            finish();
        }else{
            Toast.makeText(this, "用户名或者密码错误" , Toast.LENGTH_LONG).show();
        }
    }

    public void onInputTypeChange(View view) {
        dataBinding.loginInputPassword.setTransformationMethod(dataBinding.loginInputPassword.getTransformationMethod() == PasswordTransformationMethod.getInstance() ? HideReturnsTransformationMethod.getInstance() : PasswordTransformationMethod.getInstance());
        dataBinding.passwordEye.setImageResource(dataBinding.loginInputPassword.getTransformationMethod() == PasswordTransformationMethod.getInstance() ? R.mipmap.icon_eye_gray : R.mipmap.icon_eye_pink);
    }

    private void gotoHelp(User user){
        Intent intent;
        String roleCole = user.getRoles().get(0).getCode();
        PreferenceManager.getInstance().setRole(roleCole);
        if(!AccountUtil.isCustom(roleCole)){
            intent = new Intent(this, PlaylistActivity.class);
        }else{
            intent = new Intent(this, HelperActivity.class);
        }
        startActivity(intent);
    }




    private class MyHandler extends Handler{
        private WeakReference< LoginActivity> mAct;
        public MyHandler(LoginActivity act){
            mAct = new WeakReference<LoginActivity>(act);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what){
                case login_success:
                    LoginResult loginResult = (LoginResult) msg.obj;
                    mAct.get().loginSuccess(loginResult.getResponse());
                    break;
            }
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handler.removeCallbacksAndMessages(null);
    }

    @Override
    public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

    }

    @Override
    public void afterTextChanged(Editable editable) {
        onInputTextChange();
    }
}
